package com.weixin.controller;

import com.weixin.uitl.R;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class UploadContorller {

    @PostMapping("/upload")
    public String hello(MultipartFile file, HttpServletRequest request){

        String realPath = request.getServletContext().getRealPath("/resources/upload");
        System.out.println(realPath);
        String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")-1);

        String newName = UUID.randomUUID()+ext;
        File file1 = new File(realPath,newName);

        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/";
    }

    @PostMapping("/upload2")
    @ResponseBody
    public R testFileUpload(String desc, MultipartFile file, HttpServletRequest request){
        //得到上传路径的硬盘路径
        String realPath = request.getServletContext().getRealPath("/WEB-INF/resources/upload");
        //得到文件扩展名
        String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //新文件名
        String newFileName = UUID.randomUUID()+extension;

        File file2 = new File(realPath,newFileName);
        try {
            //存文件
            file.transferTo(file2);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok().put("path","/resources/upload/"+newFileName);
    }
}
